const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const { SESSION_SECRET_KEY } = require('./conf/secretKeys')
const koaStatic = require('koa-static')
const path = require('path')

// 路由
const errorViewRouter = require('./routes/view/error')
const userViewRouter = require('./routes/view/user')
const indexViewRouter = require('./routes/view/index')
const indexAPIRouter = require('./routes/index')
const utilsAPIRouter = require('./routes/api/utils')
const userAPIRouter = require('./routes/api/user')
const blogAPIRouter = require('./routes/api/blog')

const session = require('koa-generic-session')
const redisStore = require('koa-redis')
const { isProd } = require('./utils/env')

const { REDIS_CONF } = require('./conf/db')

// error handler
const onerrorConf = {}
if(isProd) {
    onerrorConf = {
        redirect: '/error'
    }
}
onerror(app, onerrorConf)

// middlewares
app.use(bodyparser({
    enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(koaStatic(__dirname + '/public'))
app.use(koaStatic(path.join(__dirname, '..', 'uploadFiles')))

app.use(views(__dirname + '/views', {
    extension: 'ejs'
}))

// logger
// app.use(async (ctx, next) => {
//   const start = new Date()
//   await next()
//   const ms = new Date() - start
//   console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
// })

// session 配置
app.keys = [SESSION_SECRET_KEY]
app.use(session({
    // key: 'weibo.sid', // cookie name 默认是 `koa.sid`
    // prefix: 'weibo:sess:', // redis key 的前缀, 默认是 `koa:sess:`
    cookie: {
        path: '/',
        httpOnly: true,
        maxAge: 24 * 60 * 60 * 1000,
        signed: false
    },
    // ttl: 24 * 60 * 60 * 1000,
    store: redisStore({
        all: `${REDIS_CONF.host}:${REDIS_CONF.port}`
    })
}))

// routes
app.use(indexAPIRouter.routes(), indexAPIRouter.allowedMethods())
app.use(userAPIRouter.routes(), userAPIRouter.allowedMethods())
app.use(utilsAPIRouter.routes(), utilsAPIRouter.allowedMethods())
app.use(blogAPIRouter.routes(), blogAPIRouter.allowedMethods())
app.use(indexViewRouter.routes(), indexViewRouter.allowedMethods())
app.use(userViewRouter.routes(), userViewRouter.allowedMethods())
app.use(errorViewRouter.routes(), errorViewRouter.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
    console.error('server error', err, ctx)
})

module.exports = app
